﻿using System;
using PrismNavigationFramework.Infrastructure;
using PrismNavigationFramework.Navigation;

namespace PrismNavigationFramework.MVVM
{
    public class UrlViewInitializationDataParsingService : IViewInitializationDataParsingService
    {
        private readonly IViewNavigationContextInformationParsingService _viewNavigationContextInformationParsingService;
        private readonly IKeyValuePairsParsingService _keyValuePairsParsingService;

        public UrlViewInitializationDataParsingService(IViewNavigationContextInformationParsingService viewNavigationContextInformationParsingService, IKeyValuePairsParsingService keyValuePairsParsingService)
        {
            _viewNavigationContextInformationParsingService = viewNavigationContextInformationParsingService;
            _keyValuePairsParsingService = keyValuePairsParsingService;
        }

        public ViewInitializationData Parse(object rawData)
        {
            var stringPath = rawData.ToString();

            var result = new ViewInitializationData
                             {
                                 Url = stringPath
                             };

            var navigationContext = this._viewNavigationContextInformationParsingService.ParsePath(result.Url);

            if (!string.IsNullOrEmpty(stringPath) && !string.IsNullOrEmpty(navigationContext.ViewName))
            {
                var startOfViewName = stringPath.IndexOf(navigationContext.ViewName, StringComparison.InvariantCultureIgnoreCase);
                var startOfParamsInPath = startOfViewName + navigationContext.ViewName.Length;

                if (startOfParamsInPath > 0 && startOfParamsInPath < stringPath.Length)
                {
                    result.Parameters =
                        this._keyValuePairsParsingService.ExtractKeysAndValues(stringPath.Substring(startOfParamsInPath));
                }
            }

            return result;
        }
    }
}